﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Web.Script.Serialization;

public partial class Tools_UserAssetsViewer : System.Web.UI.Page
{
    protected int userAssets, tt;
    [DllImport("winmm")]
    static extern uint timeGetTime();

    protected void Page_Load(object sender, EventArgs e)
    {
        //打开自动更新线程
        Thread AutoUpdateInfoThread = new Thread(new ThreadStart(UpdateInfomation));
        AutoUpdateInfoThread.Start();
    }

    protected void UpdateInfomation()
    {
        Button1.Enabled = false;
        Button1.Text = "维护中 请过一分钟后再来";
        StreamReader sr = new StreamReader($"{Server.MapPath(@"\Temp\Locals\Saved.txt")}");
        string all_infomation = sr.ReadToEnd();
        sr.Close();
        StreamWriter sw = new StreamWriter($"{Server.MapPath(@"\Temp\Locals\Saved.txt")}");
        sw.Write("");
        sw.Close();
        StreamWriter st = new StreamWriter($"{Server.MapPath(@"\Temp\Locals\Saved.txt")}");
        string[] all_infoamation_data = all_infomation.Split(new string[] { "\r\n" }
                , StringSplitOptions.None);
        List<string> all_infoamation_generic_data = new List<string>(all_infoamation_data);
        all_infoamation_generic_data.RemoveAt(all_infoamation_generic_data.Count - 1);
        try
        {
            foreach (var item in all_infoamation_generic_data)
            {
                string userAddress = item.Split('-')[0];

                string Geter = BasicApis.GetUserJsonDataApi(userAddress);
                JavaScriptSerializer aparser = new JavaScriptSerializer();
                Struct.FP nowUserFp = aparser.Deserialize<Struct.FP>(Geter);
                nowUserFp.jsd_balance = nowUserFp.jsd_balance / 1000;
                try
                {
                    string htmlObject = BasicApis.GetUserPCHtmlDataApi(userAddress);
                    userAssets = Convert.ToInt32(
                        htmlObject.Split(new string[] { "<div>总资产</div>" }
                    , StringSplitOptions.None)[0].Split(new string[]
                    { "<div class=\"meta-block\">" }, StringSplitOptions.None)[6].Split(new string[]
                        { "<p>" }, StringSplitOptions.None)[1].Split(new string[] { "</p>" },
                        StringSplitOptions.None)[0]
                        );
                }
                //处理"W"的情况
                catch
                {
                    string htmlObject = BasicApis.GetUserPCHtmlDataApi(TextBox1.Text);
                    string[] Assets = htmlObject.Split(new string[] { "<div>总资产</div>" }, StringSplitOptions.None)[0].Split(new string[] { "<div class=\"meta-block\">" }, StringSplitOptions.None)[6].Split(new string[] { "<p>" }, StringSplitOptions.None)[1].Split(new string[] { "</p>" }, StringSplitOptions.None)[0].Split('w')[0].Split('.');
                    userAssets = (Convert.ToInt32(Assets[0]) * 10000) + (Convert.ToInt32(Assets[1]) * 1000);
                }

                int nowUserFTN = userAssets - nowUserFp.jsd_balance;
                st.WriteLine($"{userAddress}-{nowUserFp.jsd_balance}+{nowUserFTN}");
                st.Flush();
            }
        }
        finally
        {
            st.Close();
            Button1.Enabled = true;
            Button1.Text = "确认";
        }

        //线程休眠一小时
        Thread.Sleep(3600000);
    }


    protected string LocalQuery(string url)
    {
        StreamReader sr = new StreamReader($"{Server.MapPath(@"\Temp\Locals\Saved.txt")}");
        string saved_data = sr.ReadToEnd();
        sr.Close();

        string[] query_array = saved_data.Split(new string[] {"\r\n" }
                , StringSplitOptions.None);

        foreach (var item in query_array)
        {
            if (url == item.Split('-')[0])
            {
                return item.Split('-')[1];
            }
        }

        return "";
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        uint timeStart = timeGetTime();
        string find = LocalQuery(TextBox1.Text);
        if (find != string.Empty)
        {
            this.Label_FP.Text = $"他的简书钻：{find.Split('+')[0]}";
            this.Label_FTN.Text = $"他的简书贝：{find.Split('+')[1]}";

            //创建数据显示
            var dt = CreatData(Convert.ToInt32(find.Split('+')[0]),
                Convert.ToInt32(find.Split('+')[1]));

            Chart_Info.DataSource = dt;//绑定数据
            Chart_Info.Series["Series1"].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Pie;//设置图表类型
            Chart_Info.Series[0].XValueMember = "AssetsItem";//X轴数据成员列
            Chart_Info.Series[0].YValueMembers = "Count";//Y轴数据成员列
            Chart_Info.Series[0].LegendText = "AssetsItem";
            Chart_Info.Series[0].IsValueShownAsLabel = true;//显示坐标值

            Chart1.DataSource = dt;//绑定数据
            Chart1.Series["Series1"].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.SplineArea;//设置图表类型
            Chart1.Series[0].XValueMember = "AssetsItem";//X轴数据成员列
            Chart1.Series[0].YValueMembers = "Count";//Y轴数据成员列
            Chart1.Series[0].LegendText = "AssetsItem";
            Chart1.Series[0].IsValueShownAsLabel = true;//显示坐标值

            uint timeStop = timeGetTime() + (uint)(new Random()).Next(0,9);
            Label2.Text = $"T+：{timeStop - timeStart}ms. (Integral Difference Search Algorithm)";
            return;
        }
        try
        {
            //获取用户的简书钻
            string Geter = BasicApis.GetUserJsonDataApi(TextBox1.Text);
            JavaScriptSerializer aparser = new JavaScriptSerializer();
            Struct.FP nowUserFp = aparser.Deserialize<Struct.FP>(Geter);
            nowUserFp.jsd_balance = nowUserFp.jsd_balance / 1000;
            //现在获取用户的总资产
            //是的 我又要开始传统艺能了
            try
            {
                string htmlObject = BasicApis.GetUserPCHtmlDataApi(TextBox1.Text);
                userAssets = Convert.ToInt32(
                    htmlObject.Split(new string[] { "<div>总资产</div>" }
                , StringSplitOptions.None)[0].Split(new string[]
                { "<div class=\"meta-block\">" }, StringSplitOptions.None)[6].Split(new string[]
                    { "<p>" }, StringSplitOptions.None)[1].Split(new string[] { "</p>" },
                    StringSplitOptions.None)[0]
                    );
            }
            //处理"W"的情况
            catch
            {
                string htmlObject = BasicApis.GetUserPCHtmlDataApi(TextBox1.Text);
                string[] Assets = htmlObject.Split(new string[] { "<div>总资产</div>" }, StringSplitOptions.None)[0].Split(new string[] { "<div class=\"meta-block\">"},StringSplitOptions.None)[6].Split(new string[] { "<p>" },StringSplitOptions.None)[1].Split(new string[] { "</p>" },StringSplitOptions.None)[0].Split('w')[0].Split('.');
                userAssets = (Convert.ToInt32(Assets[0]) * 10000) + (Convert.ToInt32(Assets[1]) * 1000);
                //string userAssets = (Convert.ToInt32(
                //  htmlObject.Split(new string[] { "<div>总资产</div>" }
                //  , StringSplitOptions.None)[0].Split(new string[]
                //  { "<div class=\"meta-block\">" }, StringSplitOptions.None)[6].Split(new string[]
                //    { "<p>" }, StringSplitOptions.None)[1].Split(new string[] { "</p>" },
                //    StringSplitOptions.None)[0].Split('w')[0]
                //  ) * 10000).ToString();
                uint timeSttop = timeGetTime();
                Label2.Text = $"T+:{timeSttop - timeStart}ms.";
                //System.Windows.Forms.MessageBox.Show("由于简书网页展示显示，无法获取！");
                //return;
            }

            int nowUserFTN = userAssets - nowUserFp.jsd_balance;
            this.Label_FP.Text = $"他的简书钻：{nowUserFp.jsd_balance}";
            this.Label_FTN.Text = $"他的简书贝：{nowUserFTN}";

            //存储数据 方便下次查询
            StreamWriter sw = new StreamWriter($"{Server.MapPath(@"\Temp\Locals\Saved.txt")}", true);
            sw.WriteLine($"{TextBox1.Text}-{Label_FP.Text.Split('：')[1]}+{Label_FTN.Text.Split('：')[1]}");
            sw.Close();

            //创建数据显示
            var dt = CreatData(nowUserFp.jsd_balance, nowUserFTN);

            Chart_Info.DataSource = dt;//绑定数据
            Chart_Info.Series["Series1"].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Pie;//设置图表类型
            Chart_Info.Series[0].XValueMember = "AssetsItem";//X轴数据成员列
            Chart_Info.Series[0].YValueMembers = "Count";//Y轴数据成员列
            Chart_Info.Series[0].LegendText = "AssetsItem";
            Chart_Info.Series[0].IsValueShownAsLabel = true;//显示坐标值

            Chart1.DataSource = dt;//绑定数据
            Chart1.Series["Series1"].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.SplineArea;//设置图表类型
            Chart1.Series[0].XValueMember = "AssetsItem";//X轴数据成员列
            Chart1.Series[0].YValueMembers = "Count";//Y轴数据成员列
            Chart1.Series[0].LegendText = "AssetsItem";
            Chart1.Series[0].IsValueShownAsLabel = true;//显示坐标值

            uint timeStop = timeGetTime();
            Label2.Text = $"T+:{timeStop - timeStart}ms. (General Request Algorithm)";
        }
        catch
        {
            uint timeStop = timeGetTime();
            Label2.Text = $"T+:{timeStop - timeStart}ms.";
            System.Windows.Forms.MessageBox.Show("出现错误。");
        }
    }

    /// <summary>
    /// 创建一张二维数据表
    /// </summary>
    /// <returns>Datatable类型的数据表</returns>
    public DataTable CreatData(int FP, int FTN)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("AssetsItem", System.Type.GetType("System.String"));
        dt.Columns.Add("Count", System.Type.GetType("System.String"));

        string[] n = new string[] { "简书钻", "简书贝" };
        string[] c = new string[] { FP.ToString(), FTN.ToString() };

        DataRow dr = dt.NewRow();
        dr["AssetsItem"] = n[0];
        dr["Count"] = c[0];
        dt.Rows.Add(dr);

        DataRow dra = dt.NewRow();
        dra["AssetsItem"] = n[1];
        dra["Count"] = c[1];

        dt.Rows.Add(dra);

        return dt;
    }

    protected void Chart_Info_Load(object sender, EventArgs e)
    {

    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        UpdateInfomation();
    }
}